/*数据库操作*/
/*http请求*/
const rp = require('request-promise');
/*登录信息校验*/
const tokenvilidate = require('../../common/tokenvilidate.js');
/*数据库工具*/
const basics_db = require('../../dbhelper/basics_db.js');
/*淘宝客工具*/
const tbkUtil = require('../../../utils/tbk_util.js');
/*通用工具*/
const jason_tools = require('../../../utils/jason_tools.js');

/*根参数*/
const appkey = '28243418';
const appsecret = '8acfffd32b0f66ebaae5863ef57ab771';
/* 淘宝官方 */
const uri = 'http://gw.api.taobao.com/router/rest';

/**
 * Sign API request.
 * see http://open.taobao.com/doc/detail.htm?id=111#s6
 *
 * @param  {Object} params
 * @return {String} sign string
 */
function sign(params) {
    var sorted = Object.keys(params).sort();
    var basestring = appsecret;
    for (var i = 0, l = sorted.length; i < l; i++) {
        var k = sorted[i];
        basestring += k + params[k];
    }
    basestring += appsecret;
    return tbkUtil.md5(basestring).toUpperCase();
};

/**
 * 淘宝客物料下行导购（好券推荐）
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.material = async (ctx, next) => {
    /*参数声明*/
    let query = ctx.request.body ||　{};

    /*传参声明*/
    let params = {
        app_key: appkey,
        sign_method: 'md5',
        format: 'json',
        v: '2.0',
        timestamp: tbkUtil.YYYYMMDDHHmmss(),
        method: 'taobao.tbk.dg.optimus.material'
    };
    
    let aliasData = 'mm_113916518_1166900193_109896950274'
    params.adzone_id = aliasData.split('_')[3] 

    Object.assign(params, query);
    /*签名*/
    params.sign = sign(params);

    /*函数体*/
    let options = {
        uri: uri,
        qs: params,
        headers: {
            'User-Agent': 'Request-Promise'
        },
        json: true // Automatically parses the JSON string in the response
    };
    /*请求体*/
    let res;
    await rp(options)
        .then(function (repos) {
            res = repos;
        })
        .catch(function (err) {
            res = err;
        });

    return ctx.body = res;
}
